package com.fyx.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.fyx.annotation.Log;
import com.fyx.entity.*;
import com.fyx.exception.BadRequestException;
import com.fyx.modules.system.service.DataService;
import com.fyx.modules.system.service.DeptService;
import com.fyx.modules.system.service.UserService;
import com.fyx.service.IGameDataService;
import com.fyx.until.DateUtil;
import com.fyx.utils.PageUtil;
import com.fyx.utils.SecurityUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Pageable;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Api(tags = "游戏数据")
@RestController
@RequestMapping("/api/gameData")
@RequiredArgsConstructor
public class GameDataController {
    @Autowired
    private IGameDataService iGameDataService;

    @Log("查询当前在线人数")
    @ApiOperation("查询当前在线人数")
    @GetMapping(value="getOnlineList")
    @PreAuthorize("@el.check('onlineUser:list')")
    public Map getOnlineList(ActiveDataEntity activeDataEntity, Pageable pageable){
      //  Map mapResult1 = iGameDataService.getOnlineLists(activeDataEntity,pageable);
        Map mapResult = iGameDataService.getOnlineList(activeDataEntity,pageable);
        return mapResult;
    }

    @Log("查询玩家在线信息")
    @ApiOperation("查询玩家在线信息")
    @GetMapping(value="getOnlineUserList")
    @PreAuthorize("@el.check('onlineUserList:list')")
    public Map getOnlineUserList(OnlineUserInfoEntity onlineUserInfoEntity, Pageable pageable){
        Map mapResult = iGameDataService.getOnlineUserList(onlineUserInfoEntity,pageable);
        return mapResult;
    }

    @Log("查询游戏用户")
    @ApiOperation("查询游戏用户")
    @GetMapping(value = "gameUser")
    @PreAuthorize("@el.check('gameUser:list')")
    public Map gameUser(UserEntity userEntity, Pageable pageable){
        Map mapResult = iGameDataService.gameUser(userEntity,pageable);
        return mapResult;
    }

    @Log("查询单用户")
    @ApiOperation("查询dan用户")
    @PostMapping(value = "gameOneUser")
    @PreAuthorize("@el.check('gameUser:list')")
    public User1Entity gameOneUser(@Validated @RequestBody User1Entity userEntity){

        User1Entity mapResult = iGameDataService.gameOneUser(userEntity);
        System.out.println(mapResult);
        return mapResult;
    }

    @Log("查询游戏用户")
    @ApiOperation("查询游戏用户")
    @GetMapping("gameUser3")
    @PreAuthorize("@el.check('gameUser3:list')")
    public Map gameUser3(UserEntity userEntity, Pageable pageable){
        Map mapResult = new HashMap();
        if (userEntity.getUserid()!=null
                ||userEntity.getNickname()!=null
                ||userEntity.getGold1()!=0
                || userEntity.getGold2()!=0
                ||userEntity.getDiamond1()!=0
                ||userEntity.getDiamond2()!=0
                ||userEntity.getBankgold1()!=0
                ||userEntity.getBankgold2()!=0
                ||userEntity.getQregTime()!=null
                ||userEntity.getMarkNum()>0
                ||userEntity.getPhone_idfa()!=null
                ||userEntity.getLast_ip()!=null
                ||userEntity.getIsForbid()!=null
        ){
            mapResult = iGameDataService.gameUser(userEntity,pageable);
        }else {
            mapResult.put("content",new ArrayList<UserEntity>());
            mapResult.put("totalElements",0);
            mapResult.put("countData",new ArrayList<UserEntity>());
        }

        return mapResult;
    }

    @Log("查询7日内登陆玩家")
    @ApiOperation("查询7日内登陆玩家")
    @GetMapping(value = "gameUser4")
    @PreAuthorize("@el.check('gameUser4:list')")
    public Map gameUser4(UserEntity userEntity, Pageable pageable){
        Map mapResult = iGameDataService.gameUser4(userEntity,pageable);
        return mapResult;
    }

    @Log("编辑游戏玩家")
    @ApiOperation("编辑游戏玩家")
    @PostMapping(value = "updateGameUser")
    @PreAuthorize("@el.check('gameUser:updateGameUser')")
    public ResponseEntity<Object> updateGameUser(@Validated @RequestBody User1Entity userEntity){
       boolean result= iGameDataService.updateGameUser(userEntity);
       if (result){
        return new ResponseEntity<>(HttpStatus.OK);}else {
           return new ResponseEntity<>(HttpStatus.FORBIDDEN);
       }
    }

    @Log("发送邮件")
    @ApiOperation("发送邮件")
    @PostMapping(value = "sendEmail")
    @PreAuthorize("@el.check('gameUser:sendEmail')")
    public ResponseEntity<Object> sendEmail(@Validated @RequestBody CheckListEntity checkListEntity){
        iGameDataService.sendEmail(checkListEntity);
        return new ResponseEntity<>(HttpStatus.NO_CONTENT);
    }

    @Log("全服发送邮件")
    @ApiOperation("全服发送邮件")
    @PostMapping(value = "sendAllEmail")
    @PreAuthorize("@el.check('gameUser:sendAllEmail')")
    public ResponseEntity<Object> sendAllEmail(@Validated @RequestBody CheckListEntity checkListEntity){
        iGameDataService.sendEmail(checkListEntity);
        return new ResponseEntity<>(HttpStatus.NO_CONTENT);
    }

    @Log("封号")
    @ApiOperation("封号")
    @PostMapping(value = "forbidUser")
    @PreAuthorize("@el.check('gameUser:forbidUser')")
    public ResponseEntity<Object> forbidUser(@Validated @RequestBody UserEntity userEntity) throws IOException {
       
        iGameDataService.forbidUser(userEntity);
        return new ResponseEntity<>(HttpStatus.NO_CONTENT);
    }

    @Log("解封")
    @ApiOperation("解封")
    @PostMapping(value = "openUser")
    @PreAuthorize("@el.check('gameUser:openUser')")
    public ResponseEntity<Object> openUser(@Validated @RequestBody UserEntity userEntity) throws IOException {

        iGameDataService.openUser(userEntity.getUserid(),userEntity.getFlag());
        return new ResponseEntity<>(HttpStatus.NO_CONTENT);
    }

    @Log("标记玩家")
    @ApiOperation("标记玩家")
    @PostMapping(value = "signUser")
    @PreAuthorize("@el.check('gameUser:signUser')")
    public ResponseEntity<Object> signUser(@RequestBody UserEntity userEntity) throws IOException {
        iGameDataService.signUser(userEntity);
        return new ResponseEntity<>(HttpStatus.NO_CONTENT);
    }

    @Log("无效玩家")
    @ApiOperation("无效玩家")
    @PostMapping(value = "cancelUser")
    @PreAuthorize("@el.check('gameUser:cancelUser')")
    public ResponseEntity<Object> cancelUser(@RequestBody UserEntity userEntity) throws IOException {
        System.out.println(userEntity);
        iGameDataService.cancelUser(userEntity);
        return new ResponseEntity<>(HttpStatus.NO_CONTENT);
    }

    @Log("取消标记")
    @ApiOperation("取消标记")
    @PostMapping(value = "cancelSign")
    @PreAuthorize("@el.check('gameUser:cancelSign')")
    public ResponseEntity<Object> cancelSign(@RequestBody UserEntity userEntity) throws IOException {
        iGameDataService.cancelSign(userEntity);
        return new ResponseEntity<>(HttpStatus.NO_CONTENT);
    }

    @Log("声望设置")
    @ApiOperation("声望设置")
    @PostMapping(value = "setFrame")
    @PreAuthorize("@el.check('gameUser:frame')")
    public ResponseEntity<Object> frame(@RequestBody String id) throws IOException {
        JSONObject jsonObject=JSONObject.parseObject(id);
        String userid=jsonObject.getString("userid");
        int frame=jsonObject.getIntValue("frame");
        if(frame>0) {
            iGameDataService.frame(userid, frame);
        }
        return new ResponseEntity<>(HttpStatus.NO_CONTENT);
    }

    @Log("局数限制")
    @ApiOperation("局数限制")
    @PostMapping(value = "inningsLimit")
    @PreAuthorize("@el.check('gameUser:inningsLimit')")
    public ResponseEntity<Object> inningsLimit(@RequestBody UserEntity userEntity) throws IOException {
        iGameDataService.inningsLimit(userEntity);
        return new ResponseEntity<>(HttpStatus.NO_CONTENT);
    }

    @Log("局数胜率")
    @ApiOperation("局数胜率")
    @PostMapping(value = "inningsWin")
    @PreAuthorize("@el.check('gameUser:inningsWin')")
    public ResponseEntity<Object> inningsWin(@RequestBody JSONObject jsonObject) throws IOException {
        System.out.println("jsonObject is =========="+jsonObject);
        iGameDataService.inningsWin(jsonObject);
        return new ResponseEntity<>(HttpStatus.OK);
    }



    @Log("匹配机器人开关")
    @ApiOperation("匹配机器人开关")
    @PostMapping(value = "robotSwitch")
    @PreAuthorize("@el.check('gameUser:robotSwitch')")
    public String robotSwitch() throws IOException {
        String flag =iGameDataService.robotSwitch();
        return flag;
    }

    @Log("标记金币")
    @ApiOperation("标记金币")
    @PostMapping(value = "markGold")
    @PreAuthorize("@el.check('gameUser:markGold')")
    public ResponseEntity<Object> markGold(@RequestBody UserEntity userEntity) throws IOException {
        iGameDataService.markGold(userEntity);
        return new ResponseEntity<>(HttpStatus.NO_CONTENT);
    }

    private final DeptService deptService;
    private final DataService dataService;
    private final UserService userService;

    @Log("查询嘻嘻币记录")
    @ApiOperation("查询嘻嘻币记录")
    @GetMapping(value = "goldRecord")
    @PreAuthorize("@el.check('goldRecord:list')")
    public Map goldRecord(GoldRecEntity goldRecEntity, Pageable pageable){
        if (!ObjectUtils.isEmpty(goldRecEntity.getDeptId())) {
            goldRecEntity.getDeptIds().add(goldRecEntity.getDeptId());
            goldRecEntity.getDeptIds().addAll(deptService.getDeptChildren(deptService.findByPid(goldRecEntity.getDeptId())));
        }
        List<Long> dataScopes = dataService.getDeptIds(userService.findByName(SecurityUtils.getCurrentUsername()));

        if (!CollectionUtils.isEmpty(goldRecEntity.getDeptIds()) && !CollectionUtils.isEmpty(dataScopes)){
            // 取交集
            goldRecEntity.getDeptIds().retainAll(dataScopes);
        } else {
            // 否则取并集
            goldRecEntity.getDeptIds().addAll(dataScopes);
        }
        Map mapResult = iGameDataService.goldRecord(goldRecEntity,pageable);
        return mapResult;
    }

    @Log("查询钻石记录")
    @ApiOperation("查询钻石记录")
    @GetMapping(value="diamondRecord")
    @PreAuthorize("@el.check('dimondRecord:list')")
    public Map diamondRecord(DiamondRecEntity diamondRecEntity, Pageable pageable){
        if(diamondRecEntity.getQTime()!=null){
            long time1 =diamondRecEntity.getQTime().get(0).getTime()/1000;
            long time2 =diamondRecEntity.getQTime().get(1).getTime()/1000;
            String qTime1 = DateUtil.timeStamp2Date(time1+"","yyyy-MM-dd ");
            String qTime2 = DateUtil.timeStamp2Date(time2+"","yyyy-MM-dd ");
            qTime1=qTime1.replace("-","").trim().substring(0,6);
            qTime2=qTime2.replace("-","").trim().substring(0,6);
            if(!qTime1.equals(qTime2)){
                throw new BadRequestException("搜索时间只能是同年同月");
            }
        }
        if(diamondRecEntity.getBeginTime()!=null&&diamondRecEntity.getEndTime()!=null){
            long time1 =diamondRecEntity.getBeginTime().getTime()/1000;
            long time2 =diamondRecEntity.getEndTime().getTime()/1000;
            String qTime1 = DateUtil.timeStamp2Date(time1+"","yyyy-MM-dd ");
            String qTime2 = DateUtil.timeStamp2Date(time2+"","yyyy-MM-dd ");
            qTime1=qTime1.replace("-","").trim().substring(0,6);
            qTime2=qTime2.replace("-","").trim().substring(0,6);
            if(!qTime1.equals(qTime2)){
                throw new BadRequestException("搜索时间只能是同年同月");
            }
        }
        if (!ObjectUtils.isEmpty(diamondRecEntity.getDeptId())) {
            diamondRecEntity.getDeptIds().add(diamondRecEntity.getDeptId());
            diamondRecEntity.getDeptIds().addAll(deptService.getDeptChildren(deptService.findByPid(diamondRecEntity.getDeptId())));
        }
        List<Long> dataScopes = dataService.getDeptIds(userService.findByName(SecurityUtils.getCurrentUsername()));

        if (!CollectionUtils.isEmpty(diamondRecEntity.getDeptIds()) && !CollectionUtils.isEmpty(dataScopes)){
            // 取交集
            diamondRecEntity.getDeptIds().retainAll(dataScopes);
        } else {
            // 否则取并集
            diamondRecEntity.getDeptIds().addAll(dataScopes);
        }
        Map mapResult = iGameDataService.diamondRecord(diamondRecEntity,pageable);
        return mapResult;
    }

    @Log("查询钻石统计")
    @ApiOperation("查询钻石统计")
    @GetMapping(value="dimondCount")
    @PreAuthorize("@el.check('dimondCount:list')")
    public Map dimondCount(DiamondCount diamondCount, Pageable pageable){
        Map mapResult = iGameDataService.dimondCount(diamondCount,pageable);
        return mapResult;
    }

    @Log("查询道具统计")
    @ApiOperation("查询道具统计")
    @GetMapping(value = "propsCount")
    @PreAuthorize("@el.check('propsCount:list')")
    public Map propsCount(UserEntity userEntity, Pageable pageable){
        Map mapResult = iGameDataService.propsCount(userEntity,pageable);
        return mapResult;
    }

    @Log("银行嘻嘻币统计")
    @ApiOperation("银行嘻嘻币统计")
    @GetMapping(value = "bankInfo")
    @PreAuthorize("@el.check('bankInfo:list')")
    public ResponseEntity<Object> bankInfo(BankInfoEntity bankInfoEntity, Pageable pageable){
        Map mapResult = iGameDataService.bankInfo(bankInfoEntity,pageable);
        return new ResponseEntity<>(PageUtil.toPage(mapResult.get("list"),mapResult.get("total")), HttpStatus.OK);
      //  return mapResult;
    }

    @Log("查询银行嘻嘻币记录")
    @ApiOperation("查询银行嘻嘻币记录")
    @GetMapping(value = "bankGoldRecord")
    @PreAuthorize("@el.check('bankGoldRecord:list')")
    public Map query(BankGoldRecEntity bankGoldRecEntity, Pageable pageable){
        if(bankGoldRecEntity.getQTime()!=null){
            long time1 =bankGoldRecEntity.getQTime().get(0).getTime()/1000;
            long time2 =bankGoldRecEntity.getQTime().get(1).getTime()/1000;
            String qTime1 = DateUtil.timeStamp2Date(time1+"","yyyy-MM-dd ");
            String qTime2 = DateUtil.timeStamp2Date(time2+"","yyyy-MM-dd ");
            qTime1=qTime1.replace("-","").trim().substring(0,6);
            qTime2=qTime2.replace("-","").trim().substring(0,6);
            if(!qTime1.equals(qTime2)){
                throw new BadRequestException("搜索时间只能是同年同月");
            }
        }

        if(bankGoldRecEntity.getBeginTime()!=null&&bankGoldRecEntity.getEndTime()!=null){
            long time1 =bankGoldRecEntity.getBeginTime().getTime()/1000;
            long time2 =bankGoldRecEntity.getEndTime().getTime()/1000;
            String qTime1 = DateUtil.timeStamp2Date(time1+"","yyyy-MM-dd ");
            String qTime2 = DateUtil.timeStamp2Date(time2+"","yyyy-MM-dd ");
            qTime1=qTime1.replace("-","").trim().substring(0,6);
            qTime2=qTime2.replace("-","").trim().substring(0,6);
            if(!qTime1.equals(qTime2)){
                throw new BadRequestException("搜索时间只能是同年同月");
            }
        }

        Map mapResult = iGameDataService.bankGoldRecord(bankGoldRecEntity,pageable);
        return mapResult;
    }

    @Log("查询道具记录")
    @ApiOperation("查询道具记录")
    @GetMapping(value = "propsRecord")
    @PreAuthorize("@el.check('propsRecord:list')")
    public Map query(PropsRecEntity propsRecEntity, Pageable pageable){
        if(propsRecEntity.getQTime()!=null){
            long time1 =propsRecEntity.getQTime().get(0).getTime()/1000;
            long time2 =propsRecEntity.getQTime().get(1).getTime()/1000;
            String qTime1 = DateUtil.timeStamp2Date(time1+"","yyyy-MM-dd ");
            String qTime2 = DateUtil.timeStamp2Date(time2+"","yyyy-MM-dd ");
            qTime1=qTime1.replace("-","").trim().substring(0,6);
            qTime2=qTime2.replace("-","").trim().substring(0,6);
            if(!qTime1.equals(qTime2)){
                throw new BadRequestException("搜索时间只能是同年同月");
            }
        }

        if(propsRecEntity.getBeginTime()!=null&&propsRecEntity.getEndTime()!=null){
            long time1 =propsRecEntity.getBeginTime().getTime()/1000;
            long time2 =propsRecEntity.getEndTime().getTime()/1000;
            String qTime1 = DateUtil.timeStamp2Date(time1+"","yyyy-MM-dd ");
            String qTime2 = DateUtil.timeStamp2Date(time2+"","yyyy-MM-dd ");
            qTime1=qTime1.replace("-","").trim().substring(0,6);
            qTime2=qTime2.replace("-","").trim().substring(0,6);
            if(!qTime1.equals(qTime2)){
                throw new BadRequestException("搜索时间只能是同年同月");
            }
        }
        if (!ObjectUtils.isEmpty(propsRecEntity.getDeptId())) {
            propsRecEntity.getDeptIds().add(propsRecEntity.getDeptId());
            propsRecEntity.getDeptIds().addAll(deptService.getDeptChildren(deptService.findByPid(propsRecEntity.getDeptId())));
        }
        List<Long> dataScopes = dataService.getDeptIds(userService.findByName(SecurityUtils.getCurrentUsername()));

        if (!CollectionUtils.isEmpty(propsRecEntity.getDeptIds()) && !CollectionUtils.isEmpty(dataScopes)){
            // 取交集
            propsRecEntity.getDeptIds().retainAll(dataScopes);
        } else {
            // 否则取并集
            propsRecEntity.getDeptIds().addAll(dataScopes);
        }
        Map mapResult = iGameDataService.propsRecord(propsRecEntity,pageable);
        return mapResult;
    }

    @Log("查询绑定玩家数量")
    @ApiOperation("查询绑定玩家数量")
    @GetMapping(value = "bindPlayers")
    @PreAuthorize("@el.check('bindPlayers:list')")
    public Map bindPlayers(BindPlayer bindPlayer, Pageable pageable){
        Map mapResult = iGameDataService.bindPlayers(bindPlayer,pageable);
        return mapResult;
    }

    @Log("绑定玩家来源")
    @ApiOperation("绑定玩家来源")
    @GetMapping(value = "shareSeat")
    @PreAuthorize("@el.check('shareSeat:list')")
    public Map shareSeat(ShareSeat shareSeat, Pageable pageable) throws IOException {
        Map mapResult = iGameDataService.getShareSeat(shareSeat,pageable);
        return mapResult;
    }

    @PostMapping(value = "getShareSeat")
    @PreAuthorize("@el.check('shareSeat:list')")
    public List<ShareSeat> getShareSeat(@Validated @RequestBody Integer time){
        List<ShareSeat> getMaiAdInfo = iGameDataService.getShareSeat(time);
        return getMaiAdInfo;
    }

    @Log("标记在线玩家")
    @ApiOperation("标记在线玩家")
    @GetMapping(value="signPlayers")
    @PreAuthorize("@el.check('signPlayers:list')")
    public String query(UserEntity userEntity, Pageable pageable) throws IOException {
        Map mapResult = iGameDataService.signPlayers(userEntity,pageable);
        return  JSON.toJSONString(mapResult);
    }

    @Log("查询各局数据")
    @ApiOperation("查询各局数据")
    @GetMapping(value="GamesRoundInfo")
    @PreAuthorize("@el.check('GamesRoundInfo:list')")
    public Map GamesRoundInfo(GamesInfoEntity gamesInfoEntity, Pageable pageable) throws IOException {
        Map mapResult = iGameDataService.GamesRoundInfo(gamesInfoEntity,pageable);
        return  mapResult;
    }


    @Log("查询各房间活跃玩家")
    @ApiOperation("查询各房间活跃玩家")
    @GetMapping(value="roomsPlayers")
    @PreAuthorize("@el.check('roomsPlayers:list')")
    public Map roomsPlayers(RoomsUserInfo roomsUserInfo, Pageable pageable) throws IOException {
        Map mapResult = iGameDataService.getRoomsList(roomsUserInfo,pageable);
        return  mapResult;
    }



    @PostMapping(value = "getRoomsPlayers")
    @PreAuthorize("@el.check('roomsPlayers:list')")
    public List<RoomsUserInfo> getRoomsPlayers(@Validated @RequestBody JSONObject jsonObject){
        String channel= jsonObject.getString("channel");
        Integer time=Integer.valueOf(jsonObject.getString("time")) ;
        List<RoomsUserInfo> getRoomsPlayers = iGameDataService.getRoomsList(time,channel);
        return getRoomsPlayers;
    }

    @Log("查询各房间分布图")
    @ApiOperation("查询各房间分布图")
    @GetMapping(value="playerCategory")
    @PreAuthorize("@el.check('playerCategory:list')")
    public Map playerNumber(PlayerNumber playerNumber, Pageable pageable) throws IOException {
        Map mapResult = iGameDataService.getPlayerNumber(playerNumber,pageable);
        return  mapResult;
    }



    @Log("绑定玩家来源")
    @ApiOperation("绑定玩家来源")
    @GetMapping(value = "brokeList")
    @PreAuthorize("@el.check('brokeList:list')")
    public Map brokeList(BrokeInfo brokeInfo, Pageable pageable) throws IOException {
        Map mapResult = iGameDataService.getBrokeList(brokeInfo,pageable);
        return mapResult;
    }

    @PostMapping(value = "getBrokeList")
    @PreAuthorize("@el.check('brokeList:list')")
    public List<BrokeInfo> getBroke(@Validated @RequestBody JSONObject jsonObject){
        String channel= jsonObject.getString("channel");
        Integer time=Integer.valueOf(jsonObject.getString("time")) ;
        List<BrokeInfo> getBrokeList = iGameDataService.getBrokeList(time,channel);
        return getBrokeList;
    }

    @Log("绑定人均玩家")
    @ApiOperation("绑定人均玩家")
    @GetMapping(value = "getAvgUserInfo")
    @PreAuthorize("@el.check('avgUserInfo:list')")
    public Map getAvgUserInfo(AvgUserDayInfo avgUserDayInfo, Pageable pageable) throws IOException {
        Map mapResult = iGameDataService.getAvgUserInfo(avgUserDayInfo,pageable);
        return mapResult;
    }

    @Log("绑定人均玩家")
    @ApiOperation("绑定人均玩家")
    @GetMapping(value = "getChargeUserRateLtvInfo")
    @PreAuthorize("@el.check('chargeUserRateLtvInfo:list')")
    public Map getChargeUserRateLtvInfo(UserPayRateInfo userPayRateInfo, Pageable pageable) throws IOException {
        Map mapResult = iGameDataService.getChargeUserRateLtvInfo(userPayRateInfo,pageable);
        return mapResult;
    }

}
